﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Lists;

namespace ReportGenerators.QuanLyKho
{
    public partial class FrmThamSoThongKeHangTon : BasicForms.FrmThamSoBaoCao
    {
        public FrmThamSoThongKeHangTon()
        {
            InitializeComponent();
        }

        private void FrmThamSoThongKeHangTon_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;
            #region cmbKho
            DataView dvKho = DanhMucKho.GetAll().DataView;
            cmbKho.DataSource = dvKho;
            cmbKho.DisplayColumn = "Ten";
            cmbKho.ValueColumn = "ID";
            cmbKho.AddVisibleColumn("Ma", "Mã");
            cmbKho.AddVisibleColumn("Ten", "Tên");
            cmbKho.Buttons[1].Visible = false;
            #endregion
        }

        private void cmbKho_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
                cmbKho.EditValue = null;
        }

        protected override void PrepareDataForReport()
        {
            Kho selectedKho = null;
            if (cmbKho.EditValue is Guid || cmbKho.Text != "")
            {
                selectedKho = DanhMucKho.Instance.GetByID((Guid)cmbKho.EditValue);
            }
            else
            {
                MessageBox.Show("Phải chọn kho");
                cmbKho.Focus();
            }
            DateTime dtThoiDiemBaoCao = dtNgayKetThuc.DateTime;

            BasicForms.FrmProgressBarDev.StartShowProgress();

            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            ReportTemplates.QuanLyKho.ThongKeHangTonCTSHN.DsThongKeHangTon ds = new ReportTemplates.QuanLyKho.ThongKeHangTonCTSHN.DsThongKeHangTon();
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandTimeout = GeneralLibs.Config.TimeOut;
                SqlDataAdapter da = null;

                cmd.CommandText = "Select_ThongTinDoanhNghiep2";
                cmd.Parameters.Clear();
                da = new SqlDataAdapter(cmd);
                da.Fill(ds.ThongTinDoanhNghiep);

                DataTable dtChiTietTongHopNhapXuatTon = ds.ChiTietThongKeHangTon;
                dtChiTietTongHopNhapXuatTon.Rows.Add(dtChiTietTongHopNhapXuatTon.NewRow());
                dtChiTietTongHopNhapXuatTon.Rows[0]["KyBaoCao"] = string.Format("Thời điểm {0}/{1}/{2}", dtThoiDiemBaoCao.Day, dtThoiDiemBaoCao.Month, dtThoiDiemBaoCao.Year);
                dtChiTietTongHopNhapXuatTon.Rows[0]["TenKho"] = selectedKho.Ten;

                ThoiDiemKhoaSo thoiDiemKhoaSoGanNhat = DanhMucThoiDiemKhoaSo.Instance.GetThoiDiemKhoaSoGanNhat(dtThoiDiemBaoCao);
                if (thoiDiemKhoaSoGanNhat == null) throw new GeneralLibs.CustomException("Không có thời điểm khóa sổ trước " + dtThoiDiemBaoCao.ToString());

                DataTable dtBienDongHang = new DataTable();
                cmd.CommandText = "SELECT VatTuHangHoaID, SUM(SoLuongNhap) - SUM(SoLuongXuat) AS BienDong \n" +
                                    "FROM NhatKyKhoChiCoSoLuong \n" +
                                    "WHERE KhoID = @KhoID AND @ThoiDiemDau < Ngay AND Ngay < @ThoiDiemCuoi \n" +
                                    "GROUP BY VatTuHangHoaID \n";
                cmd.Parameters.Clear();
                cmd.Parameters.AddWithValue("KhoID", selectedKho.ID);
                cmd.Parameters.AddWithValue("ThoiDiemDau", thoiDiemKhoaSoGanNhat.ThoiDiem);
                cmd.Parameters.AddWithValue("ThoiDiemCuoi", dtThoiDiemBaoCao);
                da = new SqlDataAdapter(cmd);
                da.Fill(dtBienDongHang);

                DataTable dtKhoanMucTongHopNhapXuatTon = ds.KhoanMucThongKeHangTon;
                int processedCounter = 0;
                foreach (VatTuHangHoa vatTuHangHoa in DanhMucVatTuHangHoa.Instance)
                {
                    DataRow khoanMucRow = dtKhoanMucTongHopNhapXuatTon.NewRow();
                    khoanMucRow["MaVatTuHangHoa"] = vatTuHangHoa.Ma;
                    khoanMucRow["TenVatTuHangHoa"] = vatTuHangHoa.Ten;
                    khoanMucRow["DonViTinh"] = vatTuHangHoa.DonViTinh;
                    khoanMucRow["GiaBia"] = vatTuHangHoa.GiaBia;

                    TonKho tonDauKy =  TonKho.GetTonDauKyTheoKho(cmd, thoiDiemKhoaSoGanNhat.ID, selectedKho.ID, vatTuHangHoa.ID);

                    DataRow[] rows = dtBienDongHang.Select(string.Format("VatTuHangHoaID = '{0}'", vatTuHangHoa.ID));
                    decimal bienDong = 0;
                    if (rows.Length > 0) bienDong = (decimal)rows[0]["BienDong"];


                    khoanMucRow["SoLuongCuoiKy"] = tonDauKy.SoLuong + bienDong;
                    khoanMucRow["GiaTriCuoiKy"] = vatTuHangHoa.GiaBia * (decimal)khoanMucRow["SoLuongCuoiKy"] ;

                    if (!chkChiHienThiHangTon.Checked || (decimal)khoanMucRow["SoLuongCuoiKy"] != 0)
                        dtKhoanMucTongHopNhapXuatTon.Rows.Add(khoanMucRow);

                    BasicForms.FrmProgressBarDev.Status = string.Format("Đã xử lý {0}/{1} thuốc", ++processedCounter, DanhMucVatTuHangHoa.Instance.Count);
                }
             
                _Report = new ReportTemplates.QuanLyKho.ThongKeHangTonCTSHN.RptThongKeHangTon();
                _Report.SetDataSource(ds);
            }
            catch (GeneralLibs.CustomException cusEx)
            {
                MessageBox.Show(cusEx.Message);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
            }

            BasicForms.FrmProgressBarDev.FinishShowProgress();
        }

        protected override void PrintReport()
        {
            if (_Report != null)
            {
                ReportTemplates.FrmPrintReport frm = new ReportTemplates.FrmPrintReport(_Report, "Tổng hợp nhập xuất tồn");
                frm.Show();
            }
        }

        private void cmbKho_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;
        }
    }
}
